import React from 'react';
import {
  Select,
  Form,
  Card,
  Button,
  Row,
  Col,
  Table,
  Input,
  Pagination,
  message,
  Icon,
  Popconfirm,
} from 'antd';
import moment from 'moment';
import BaseComponent from '@/components/BaseComponent';
import style from './index.css';
import AddButton from './AddButton';
import Modification from './Modification';
import { saveAs } from 'file-saver';
import { connect } from 'dva';
import importPngFlag from '@/assets/import.png';
import UploadComponent from '@/components/UploadComponent';
import FileUpload from './FileUpload';
import PermissionsWidget from '@/components/PermissionsWidget';

@connect(({ user }) => ({
  currentUser: user.currentUser,
}))
export default class index extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      expand: false,
      data: [],
      total: 0,
      current: 0,
      form: {},
      ids: [],
      provinceIdData: [],
      cityIdData: [],
      districtIdData: [],
    };
  }

  provinceIdChange = value => {
    this.setState(
      params => ({
        form: {
          ...params.form,
          provinceId: value,
        },
      }),
      () => {
        this.getCity({ level: 2, parentCode: value });
      }
    );
  };
  cityIdChange = value => {
    this.setState(
      params => ({
        form: {
          ...params.form,
          cityId: value,
        },
      }),
      () => {
        this.getCity({ level: 3, parentCode: value });
      }
    );
  };

  districtIdChange = value => {
    this.setState(params => ({
      form: {
        ...params.form,
        districtId: value,
      },
    }));
  };
  institutionNameChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        institutionName: value,
      },
    }));
  };

  screeningYearChange = e => {
    const value = e.target.value;
    this.setState(params => ({
      form: {
        ...params.form,
        screeningYear: value,
      },
    }));
  };

  componentDidMount() {
    this.getDataByPage({});
    this.getCity({ level: 1, parentCode: '1' });
  }
  //查询省
  getCity = param => {
    this.execHttp('plannedFollowUp/getCity', { ...param }).then(resp => {
      if (resp) {
        if (param.level == 1) {
          this.setState({
            provinceIdData: resp.data,
          });
        } else if (param.level == 2) {
          this.setState({
            cityIdData: resp.data,
          });
        } else if (param.level == 3) {
          this.setState({
            districtIdData: resp.data,
          });
        }
      }
    });
  };
  //分页
  getDataByPage = param => {
    this.execHttp('taskAllocation/selList', {
      user: this.props.currentUser.id,
      currentPage: 1,
      pageSize: 10,
      ...param,
    }).then(resp => {
      if (resp.success) {
        this.setState({
          data: resp.data.list,
          total: resp.data.pagination.total,
          current: resp.data.pagination.current,
        });
      }
    });
  };
  //分页切换
  onChangePagination = (page, pageSize) => {
    this.getDataByPage({
      user: this.props.currentUser.id,
      currentPage: page,
      pageSize: pageSize,
      ...this.state.form,
    });
  };
  onShowSizeChange = (current, pageSize) => {
    if (current === 0) {
      current = 1;
    }
    this.getDataByPage({
      user: this.props.currentUser.id,
      currentPage: current,
      pageSize: pageSize,
      ...this.state.form,
    });
  };

  //删除
  del = id => {
    this.execHttp('taskAllocation/del', { id }).then(resp => {
      if (resp.success) {
        message.success(resp.message);
        this.getDataByPage({});
      }
    });
  };

  //锁定
  changeStatus = (id, status) => {
    this.execHttp('followUpFormalDatabase/changeStatus', { id, status }).then(resp => {
      if (resp.success) {
        message.success(resp.message);
        this.getDataByPage({});
      }
    });
  };

  //查询
  searchClick = () => {
    this.getDataByPage(this.state.form);
  };

  //重置
  resetClick = () => {
    this.setState(
      () => ({
        form: {},
      }),
      () => {
        this.getDataByPage(this.state.form);
      }
    );
  };

  //展开与否状态切换
  handleToggle = () => {
    const { expand } = this.state;
    this.setState({ expand: !expand });
  };

  onSelectChange = selectedRowKeys => {
    this.setState({ ids: selectedRowKeys });
  };
  // 导出
  exportData = () => {
    const ids = this.state.ids.join('|');
    const hide = this.loadingMessage('正在导出数据，请稍后...');
    this.execHttp('taskAllocation/queryAllExportData', {
      ids: ids,
      ...this.state.form,
      user: this.props.currentUser.id,
    })
      .then(res => {
        hide();
        saveAs(res, '任务分配列表' + '.xlsx');
      })
      .catch(err => {
        hide();
      });
  };

  render() {
    const columns = [
      // {
      //   title: 'ID',
      //   dataIndex: 'id',
      //   key: 'id',
      // },
      {
        title: '',
        dataIndex: 'country_source',
        key: 'country_source',
        width: 1,
        fixed: 'left',
        render: (text, record) => {
          const { country_source } = record;

          // 根据country_source的值生成对应的图片元素
          let imageElement = null;

          if (country_source === '1') {
            imageElement = <img src={importPngFlag} alt="国家系统数据" title="导入" />;
          }

          // 返回包含图片元素和文本内容的行元素
          return <div>{imageElement}</div>;
        },
      },
      {
        title: '筛查年度',
        dataIndex: 'screening_year',
        key: 'screening_year',
        fixed: 'left',
      },
      {
        title: '筛查机构',
        dataIndex: 'institution',
        key: 'institution',
      },
      {
        title: '隶属省份',
        dataIndex: 'province',
        key: 'province',
      },
      {
        title: '隶属城市',
        dataIndex: 'city',
        key: 'city',
      },
      {
        title: '隶属区县',
        dataIndex: 'district',
        key: 'district',
      },
      {
        title: '开始时间',
        dataIndex: 'time_begin',
        key: 'time_begin',
        render: (text, record, index) => {
          const { time_begin } = record;
          const str = moment(time_begin).format('YYYY-MM-DD');
          return str;
        },
      },
      {
        title: '结束时间',
        dataIndex: 'time_end',
        key: 'time_end',
        render: (text, record, index) => {
          const { time_end } = record;
          const str = moment(time_end).format('YYYY-MM-DD');
          return str;
        },
      },
      {
        title: '任务量  ',
        dataIndex: 'year_task_volume',
        key: 'year_task_volume',
      },
      {
        title: '初筛任务量',
        dataIndex: 'first_screening_task_volume',
        key: 'first_screening_task_volume',
      },
      {
        title: '随访任务量',
        dataIndex: 'follow_task_volume',
        key: 'follow_task_volume',
      },
      {
        title: '封库状态',
        dataIndex: 'status',
        key: 'status',
        render: (text, record, index) => {
          const { status } = record;
          const data = [
            { id: '1', name: '未封库' },
            { id: '2', name: '已封库' },
          ];
          const str = status ? data.find(item => item.id == status) : '';
          return str.name;
        },
      },

      {
        title: '操作',
        key: 'action',
        width: 200,
        fixed: 'right',
        render: (text, record) => {
          if (record.status == 1) {
            return (
              <div className={style.actionstyle}>
                <PermissionsWidget tag={'taskAllocation:task-lock'}>
                  <Popconfirm
                    title="是否确认?"
                    onConfirm={() => {
                      this.changeStatus(record.id, 2);
                    }}
                    okText="是"
                    cancelText="否"
                  >
                    <Button type="primary" style={{ marginRight: '10px' }}>
                      锁定
                    </Button>
                  </Popconfirm>
                </PermissionsWidget>
                <Modification record={record} getDataByPage={this.getDataByPage}></Modification>
                <PermissionsWidget tag={'taskAllocation:task-delete'}>
                  <Popconfirm
                    title="是否确认?"
                    onConfirm={() => {
                      this.del(record.id);
                    }}
                    okText="是"
                    cancelText="否"
                  >
                    <Button type="danger" style={{ marginLeft: '10px' }}>
                      删除
                    </Button>
                  </Popconfirm>
                </PermissionsWidget>
              </div>
            );
          } else {
            return (
              <div className={style.actionstyle}>
                <PermissionsWidget tag={'taskAllocation:task-lock'}>
                  <Popconfirm
                    title="是否确认?"
                    onConfirm={() => {
                      this.changeStatus(record.id, 1);
                    }}
                    okText="是"
                    cancelText="否"
                  >
                    <Button type="primary" style={{ marginRight: '10px' }}>
                      解锁
                    </Button>
                  </Popconfirm>
                </PermissionsWidget>
              </div>
            );
          }
        },
      },
    ];

    const rowSelection = {
      onChange: this.onSelectChange,
    };
    const { data, total, current } = this.state;
    return (
      <div>
        <Card size="small" style={{ width: '100%' }} bordered={true} title={'任务分配'}>
          <Form layout="horizontal">
            <Row gutter={16}>
              <Col span={6}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.provinceId}
                    onChange={this.provinceIdChange}
                    placeholder="请选择所属省份"
                  >
                    {this.state.provinceIdData.map(item => (
                      <Select.Option key={item.code}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.cityId}
                    onChange={this.cityIdChange}
                    placeholder="请选择所属城市"
                  >
                    {this.state.cityIdData.map(item => (
                      <Select.Option key={item.code}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>
                  <Select
                    allowClear
                    value={this.state.form.districtId}
                    onChange={this.districtIdChange}
                    placeholder="请选择所属区/县"
                  >
                    {this.state.districtIdData.map(item => (
                      <Select.Option key={item.code}>{item.name}</Select.Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={6} style={{ textAlign: 'center' }}>
                <FileUpload getDataByPage={this.getDataByPage}></FileUpload>
                <Button
                  type="primary"
                  style={{ marginLeft: '5px', marginRight: '5px' }}
                  onClick={this.exportData}
                >
                  导出
                </Button>
                <Button type="primary" onClick={this.searchClick}>
                  查询
                </Button>
                <Button onClick={this.resetClick} style={{ marginLeft: '5px' }}>
                  重置
                </Button>
                <a style={{ marginLeft: 5, fontSize: 10 }} onClick={this.handleToggle}>
                  {this.state.expand ? '折叠' : '展开'}
                  <Icon type={this.state.expand ? 'up' : 'down'} />
                </a>
              </Col>
            </Row>

            <Row gutter={16} style={{ display: this.state.expand ? 'block' : 'none' }}>
              <Col span={6}>
                <Form.Item>
                  <Input
                    placeholder="机构名称"
                    value={this.state.form.institutionName}
                    onChange={this.institutionNameChange}
                  />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item>
                  <Input
                    placeholder="筛查年度"
                    value={this.state.form.screeningYear}
                    onChange={this.screeningYearChange}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <div style={{ width: '100%', height: '20px' }}></div>
          <PermissionsWidget tag={'taskAllocation:task-add'}>
            <AddButton getDataByPage={this.getDataByPage}></AddButton>
          </PermissionsWidget>
          <Table
            columns={columns}
            dataSource={data}
            rowSelection={rowSelection}
            rowKey="id"
            pagination={false}
            scroll={{
              x: 2000,
            }}
            size="small"
            style={{ marginTop: '20px' }}
          />
          <div
            style={{
              marginTop: '20px',
              display: 'flex',
              flexDirection: 'row-reverse',
            }}
          >
            <Pagination
              showSizeChanger={true}
              showQuickJumper
              onChange={this.onChangePagination}
              onShowSizeChange={this.onShowSizeChange}
              defaultCurrent={1}
              current={current}
              total={total}
              showTotal={total => `总共 ${total} 条`}
            />
          </div>
        </Card>
      </div>
    );
  }
}
